<template>
  <view :class="customTabbar && isIpx ? 'custom-tab-bottom-ipx' : customTabbar && !isIpx ? 'custom-tab-bottom' : ''">
    <onlineService></onlineService>
    <tabBar v-if="customTabbar === 1 && tabbarTimeout" :nowPages.sync="nowPages"></tabBar>
    <navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
    <view class="shop_cart" :style="listDataNum > 0 ? 'padding-bottom:100rpx' : ''">
      <shopCart :isIpx.sync="isIpx" :isSystem.sync="isSystem" ref="shopCart" :toTop.sync="toTop"
        @moveShopItem="handelMoveItem" @listDataNum="getlistDataNum" @navItemClick="handleNavItemClick"></shopCart>
      <view v-if="cartRecommendShow" style="padding-bottom:96rpx;padding-top:80rpx;">
        <utools-parse id="utools-parse-cart" page="cart" @triggerComponent="onTriggerComponent" @setPanel="setPanel"
          :utools-data="cartRecommendUtools" @onAddCart="onAddCart"></utools-parse>
      </view>
    </view>
  </view>
</template>
<script>
  import api from '@/api/api';
  import ShopCart from './shopCart.vue';
  import {
    USER_INFO,
    CUSTOMER_INFO,
    MERCHANT_INFO,
    SYSTEM_INFO,
    LOWER_WX_VERSION
  } from '@/utils/constant';
  import onlineService from '@/components/common/onlineService';
  import NavBar from '../../components/common/navbar';
  import TabBar from '../../components/common/tabbar';
  export default {
    config: {
      navigationStyle: 'custom',
      navigationBarTitleText: '购物车',
      enablePullDownRefresh: true
    },
    components: {
      navBar: NavBar,
      tabBar: TabBar,
      onlineService: onlineService,
      shopCart: ShopCart,
    },

    data() {
      return {
        flag: true,
        windowHeight: 0,
        customTabbar: -1,
        tabbarTimeout: false,
        isIpx: false,
        isSystem: false,
        toTop: false,
        isShowCustomNavBar: true,
        listDataNum: 0,
        // 组件所需的参数
        navbarData: {
          showCapsule: 0, //是否显示左上角图标   1表示显示    0表示不显示
          title: '购物车', //导航栏 中间的标题
          showSearchAndBack: false,
        },
        LOWER_WX_VERSION: '',
        identifier: 'cms/itemrecommend',
        nowPages: '',
        preview: false,
        cartRecommendShow: false,
        cartRecommendUtools: null, //  为你推荐 utools json
        utoolsClassGoodsLists: [],  //  utools分类商品集合数组
        cartNavIndex: 0
      };
    },

    onLoad(option) {
      this.handleUtoolsCartRecommend(option);
      this.customTabbar = this.$programSetting.customTabbar ? 1 : 0
      this.LOWER_WX_VERSION = LOWER_WX_VERSION;
      let systemInfo = uni.getStorageSync(SYSTEM_INFO);
      if (Number(systemInfo.SDKVersion) < Number(this.LOWER_WX_VERSION)) {
        this.isShowCustomNavBar = false;
      }
      const systemInfoSync = uni.getSystemInfoSync();
      this.windowHeight = systemInfoSync.windowHeight - getApp().globalData.navBarHeight;
      this.isIpx = getApp().globalData.isIpx;
      this.isSystem = getApp().globalData.isSystem;
      let pages = getCurrentPages();
      //当前页面
      var currPage = pages[pages.length - 1];
      this.nowPages = currPage.route;
      //上一级页面
      let prevPage = pages[pages.length - 2];
      if (prevPage !== undefined) {
        this.navbarData.showSearchAndBack = true;
      } else {
        this.navbarData.showSearchAndBack = false;
      }
    },
    onShow() {
      let that = this
      setTimeout(() => {
        that.tabbarTimeout = true;
      }, 400)
      // that.$commonFunction.getCartList().then((res) => { }).catch((err) => { });
      this.toTop = true;
      this.$refs.shopCart.getCartListMethod();
      getApp().cl_tracker.track('mini_program_view', {
        path: this.nowPages,
        pageName: '购物车',
      })
      // this.$refs.shopCart.viewTrack();
      this.$refs.shopCart.handleGetRecentBrowsing();
      // this.$commonSensors.viewCart(this.listData)
    },
    created: async function(option) {

    },
    //点击购物车tabber埋点
    onTabItemTap(e) {
      let text = e.text
      let clTrackPrams = {
        'c_tab': "购物车",
        'c_link_pagename': e.text,
        'c_link_path': e.pagePath
      }
      getApp().commonClTrack('c_ebmp_click_tabbar', clTrackPrams)
    },
    methods: {
      /**
       * 购物车tab切换 回调方法
       * @param {Object} index
       */
      handleNavItemClick(index) {
        this.cartNavIndex = index;
      },
      /**
       *  获取购物车为你推荐utools数据
       */
      async handleUtoolsCartRecommend(option) {
        let resData;
        if(option && option.utid) {
          //  预览
          resData = await api.getUtoolsJsonP({
            utoolsId: option.utid,
            type:'cartRecommend'
          });
        } else {
          resData = await api.getUtoolsJson({
            type: 'cartRecommend'
          });
        }
        if (resData.success && resData.data) {
          this.cartRecommendUtools = JSON.parse(resData.data);
          //商品
          const _reslists = await this.getCateGoods(this.cartRecommendUtools?.classId || 8066);
          //  购物车商品列表 都是用hdlpImgUrl字段图片
          _reslists.forEach(item=>{
            if(item?.hdlpImgUrl) item.hoverUrl = item.hdlpImgUrl;
          })
          this.utoolsClassGoodsLists = _reslists;
          this.cartRecommendShow = true;
        }
      },
      /**
       * 查询首页商品分类列表
       * @param {Object} class_id 分类id
       * @param {Object} is_sort  是否筛选
       */
      async getCateGoods(class_id, is_sort) {
        try {
          //获取商品
          let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
          let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
          let res = await this.$commonFunction.doSearchGoods(class_id, '', 1, 200, null, '', is_sort, '', '', '', '')
          let cateProductList = res.data.content; // 商品列表
          //sku实时库存查询
          let skuCodeList = [];
          for (let i = 0; i < cateProductList.length; i++) {
            skuCodeList = skuCodeList.concat(cateProductList[i].skuCodes)
          }
          let reset = await api.getAvailableBatchQty({
            method: "POST",
            header: {
              jwt: customerInfo.jwt
            },
            query: skuCodeList
            // query: JSON.stringify(skuCodeList)
          }, merchantInfo.cloudMerchantId);
          // 策略价格
          let goodsQ = null;
          if (reset.msg == "SUCCESS" && reset?.data?.length) {
            goodsQ = reset.data.filter(item => item.availableQty > 0)
          }
          let list = [];
          cateProductList = cateProductList.map(async item => {
            let res = await this.$commonFunction.priceRulesDeal(item.strategies, item.itemmCode)
            if (goodsQ && goodsQ.length) {
              for (let i = 0; i < goodsQ.length; i++) {
                if (item.skuCodes.indexOf(goodsQ[i].skuCode) !== -1 && goodsQ[i].availableQty > 0) {
                  item.frontQty += goodsQ[i].availableQty
                }
              }
            }
            if (res.price !== 0 && item.itemCode == res.itemCode) {
              item.price = res.price
            }
            if (res.rulesArr.length > 0 && item.itemCode == res.itemCode) {
              item.rulesArr = res.rulesArr
            }
            list.push(item)
            item.isShowMainImg = true;
            return item
          })
          return list
        } catch (err) {
          return null
        }
      },
      /**
       * utools加入购物车回调
       * @param {Object} e
       */
      async onAddCart(e) {
        const { detail: { data } } = e;
        if(!data || !data.itemId) return this.$refs.shopCart.handleCartToast({success:false,msg:"加入购物袋失败"});
        const merchantInfo = uni.getStorageSync('merchantInfo');
        if(!merchantInfo) return this.$refs.shopCart.handleCartToast({success:false,msg:"加入购物袋失败"});
        // 获取商品详情
        const goodsInfo = await this.getGoodsDetail(merchantInfo, data.itemId);
        if(!goodsInfo || goodsInfo.code != 1000) return this.$refs.shopCart.handleCartToast({success:false,msg:"加入购物袋失败"});
        const cartRes = await this.$commonFunction.buildProductsAddCart({
          price: goodsInfo.data.skus[0].price,
		  itemId: goodsInfo.data.itemId,
          valueId: goodsInfo.data.frontProperties[0].valueId,
          itemCode: goodsInfo.data.itemId,
          itemName:  goodsInfo.data.itemName,
          qty: 1,
          skuCode:  goodsInfo.data.skus[0].skuCode,
          skuId:  goodsInfo.data.skus[0].skuId,
        });
        //  加入购物车提示
        this.$refs.shopCart.handleCartToast(cartRes);
      },
      //商品和购物车有数埋点2
      onTriggerComponent(e) {
        try{
         this.$commonUtoolsTrack.onTriggerComponent(e);
        }catch(e){
        }
      },

      async setPanel(d = null) {

      },
      /**
       * 获取商品详情
       * @param {Object} merchantInfo
       * @param {Object} itemId
       */
      async getGoodsDetail(merchantInfo,itemId) {
      	return await api.goodsDetail({
      			query: {
      				merchant_id: merchantInfo.cloudMerchantId,
      				store_id: merchantInfo.cloudMerchantStoreId
      			}
      		},
      		itemId
      	);
      },
      getlistDataNum(num) {
        this.listDataNum = num;
      },
      handelMoveItem(e) {
        this.flag = e.scroll;
      },
    },

    onPullDownRefresh() {
      uni.showNavigationBarLoading();
      this.$refs.shopCart.getCartListMethod();
      setTimeout(function() {
        uni.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
        uni.stopPullDownRefresh(); //停止下拉动作
      }, 1200);
    }
  };
</script>
<style>
  .shop_cart {
    /* padding-bottom: 100rpx; */
    /* padding-bottom: 110rpx; */
  }
</style>
